package trigger.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Vector;

import javax.swing.JOptionPane;

import trigger.gui.LayoutGUI;
import trigger.config.Options;
import trigger.encoder.Base64;

public class IOtools
{

    private final static String SERVER_PATCH;
    private boolean proxyAuth;
    private String encodedLogin;
    private Proxy proxy = null;
    
    static{
        SERVER_PATCH = Options.getInstance().getServer();

    }

    public IOtools(){
        Options options = Options.getInstance();
        String proxyHost = options.getProxyHost().trim();
        if(proxyHost.length() > 1)  {
            proxy = new Proxy( Proxy.Type.HTTP, new InetSocketAddress(proxyHost, options.getProxyPort()));
            String proxyUsername = options.getProxyUsername();
            if(proxyUsername.length() > 0){
                proxyAuth = true;
                String login = proxyUsername+":"+options.getProxyPassword();
                encodedLogin = Base64.encodeBytes(login.getBytes());
            }else
                proxyAuth = false;
        }
    }
    
public boolean isOnline() throws SocketTimeoutException, Exception
{
	BufferedReader br;
	String resultado="";
	try
	{
		URL url = new URL(SERVER_PATCH+"/update/on-line.php");
                URLConnection urlconnection;
                if(proxy != null)
                    urlconnection = (URLConnection) url.openConnection(proxy);
                else
                    urlconnection = url.openConnection();
                String line = null;
                if(proxyAuth)
                    urlconnection.setRequestProperty("Proxy-Authorization", "Basic " + encodedLogin);
                urlconnection.setReadTimeout(Options.getInstance().getTimeoutTime() * 1000);
		br = new BufferedReader(new InputStreamReader(urlconnection.getInputStream()));
		while((line = br.readLine()) != null){resultado+=line+"\n";}
		br.close();
	}
        catch(SocketTimeoutException ex){
            throw ex;
        }
        catch(MalformedURLException mfurlex){
            mfurlex.printStackTrace();
        }
        catch(IOException ioex){
            ioex.printStackTrace();
        }
        catch(Exception ex){
            throw ex;
        }

	return resultado.trim().equals("ok")? true : false;
}

public String get(String page)
{
	BufferedReader br = null;
	String resultado="";
	try
	{
		URL url = new URL(SERVER_PATCH+page);
                URLConnection urlconnection;
                if(proxy != null)
                    urlconnection = (URLConnection) url.openConnection(proxy);
                else
                    urlconnection = url.openConnection();
                String line = null;
                if(proxyAuth)
                    urlconnection.setRequestProperty("Proxy-Authorization", "Basic " + encodedLogin);
		br = new BufferedReader(new InputStreamReader(urlconnection.getInputStream()));
		while((line = br.readLine()) != null){resultado+=line+"\n";}
		br.close();
	}
	catch(Exception ex)
	{
	}
	return resultado.trim();
}

public String post(String page,Vector<String[]> data)
{
	BufferedReader in;
	OutputStreamWriter out;
	String resultado="";
	try
		{
		URL url = new URL(SERVER_PATCH+page);
                URLConnection urlconnection;
                if(proxy != null)
                    urlconnection = (URLConnection) url.openConnection(proxy);
                else
                    urlconnection = url.openConnection();
                String line = null;                
                if(proxyAuth)
                    urlconnection.setRequestProperty("Proxy-Authorization", "Basic " + encodedLogin);
		urlconnection.setDoOutput(true);
		out = new OutputStreamWriter(urlconnection.getOutputStream());
		for(int i = 0;i<data.size();i++)
		{
			out.write(data.get(i)[0]+"="+data.get(i)[1]+"&");
		}
		out.close();
		in = new BufferedReader(new InputStreamReader(urlconnection.getInputStream()));
		while((line = in.readLine()) != null){resultado+=line+"\n";}
		in.close();
		}
	catch(Exception ex)
	{
		
	}
	return resultado.trim();
}

public void download(String page,File destination) throws Exception
{

	int length;
	LayoutGUI.layout.changeProgressBar(0);
	LayoutGUI.layout.indeterminate(false);
	LayoutGUI.layout.visibleProgressBar(true);
	
	try
	{
	URL url = new URL(SERVER_PATCH+page);
        URLConnection urlconnection;
        if(proxy != null)
            urlconnection = (URLConnection) url.openConnection(proxy);
        else
            urlconnection = url.openConnection();
        String line = null;
        if(proxyAuth)
                    urlconnection.setRequestProperty("Proxy-Authorization", "Basic " + encodedLogin);
		try{length = Integer.parseInt(urlconnection.getHeaderField("Content-Length"));}catch(Exception ex){length=0;}
		if(length==0){LayoutGUI.layout.indeterminate(true);}
	LayoutGUI.layout.setLengthOfPb(length);
	OutputStream out = new FileOutputStream(destination);
	InputStream in = urlconnection.getInputStream();
	
	LayoutGUI.layout.setSstatus("Recebendo : "+page.substring(page.lastIndexOf("/")+1)+" - "+length/1024+" Kbs");
	
	byte[] buffer = new byte[4096];
	int l;
		while ((l = in.read(buffer)) != -1)
		{
			out.write(buffer, 0, l);
			LayoutGUI.layout.changeProgressBar(LayoutGUI.layout.getProgress()+l);
		}
	out.close();
	}
	catch(Exception ex)
	{
		LayoutGUI.layout.visibleProgressBar(false);
		throw new Exception("Fallhou ao fazer Download");
	}
	LayoutGUI.layout.visibleProgressBar(false);

}

public static boolean opcao(String positive,String negative,String title,String question)
{
Object[] options = {positive,
					negative};
int n = JOptionPane.showOptionDialog(LayoutGUI.layout,
    question,
    title,
    JOptionPane.YES_NO_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    null,
    options,
    options[0]);
    return n==0;
    
    
}


public static void showAlert(String title,String message)
{
    JOptionPane.showMessageDialog(LayoutGUI.layout, message, title, JOptionPane.INFORMATION_MESSAGE);
}

}
